package com.anrongtec.zcpt.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.callback.StringDialogCallback;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.PreferenceKey;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.logo.LoginActivity;
import com.anrongtec.zcpt.manager.APPDownloadManager;
import com.anrongtec.zcpt.manager.AppDownManagerActivity;
import com.anrongtec.zcpt.manager.AppStateManager;
import com.anrongtec.zcpt.manager.AppStateManager.AppStateListener;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.tab02.AppDetailActivity;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.art.base.util.AppManager;
import com.art.base.util.FileUtils;
import com.art.base.util.PreferenceUtils;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.lzy.okhttputils.callback.StringCallback;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.io.File;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 搜索页面
 *
 * @author cxy
 */
public class SearchActivity extends BaseActivity implements OnFocusChangeListener, OnClickListener {

    private Toolbar toolBar;
    private EditText et_search;
    private ImageView iv_search;
    private RecyclerView rv_search;

    private String info;

    private int page, totalPage;

    private ArrayList<AppModel> apps;
    private CommonAdapter<AppModel> adapter;
    /**接收安装卸载*/
    /**
     * 广播接收器, 接收安装卸载
     */
    private AppStateManager manager;
    private EmptyWrapper empty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleShow(false);
        setContentView(R.layout.activity_search);

        initToolBar();
        initViews();

        registerAppStatus();
    }

    /**
     * 注册广播接收器
     */
    private void registerAppStatus() {
        manager = new AppStateManager(SearchActivity.this);
        manager.begin(new AppStateListener() {

            @Override
            public void onAppUninstalled(String pkgName) {
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onAppRelpaced(String pkgName) {
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onAppInstalled(String pkgName) {
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (manager != null) {
            manager.unregisterListener();
        }
        super.onDestroy();
    }

    @Override
    protected void initViews() {
        et_search = (EditText) findViewById(R.id.et_toolbar_search);
        et_search.setCompoundDrawables(null, null, null, null);
        et_search.setOnFocusChangeListener(this);

        iv_search = (ImageView) findViewById(R.id.iv_toolbar);
//		iv_search.setImageResource(android.R.drawable.ic_menu_search);
        iv_search.setImageResource(R.drawable.icon_search);
        iv_search.setOnClickListener(this);

        initRecyclerView();
    }


    /**
     * 设置toolbar
     */
    private void initToolBar() {
        //toolbar
        toolBar = (Toolbar) findViewById(R.id.toolbar);
        toolBar.setTitle("");
        setSupportActionBar(toolBar);
        toolBar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getSupportActionBar().setHomeButtonEnabled(true); //这个小于4.0版本的默认值为true的。但是在4.0及其以上是false，该方法的作用：决定左上角的图标是否可以点击。没有向左的小图标。 true 图标可以点击  false 不可以点击。
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 给左上角图标的左边加上一个返回的图标 。对应ActionBar.DISPLAY_HOME_AS_UP
//		getSupportActionBar().setDisplayShowHomeEnabled(true); //使左上角图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标，对应id为android.R.id.home，对应ActionBar.DISPLAY_SHOW_HOME
        //				getSupportActionBar().setDisplayShowCustomEnabled(true); // 使自定义的普通View能在title栏显示，即actionBar.setCustomView能起作用，对应ActionBar.DISPLAY_SHOW_CUSTOM
    }

    /**
     * 初始化recyclerView
     */
    private void initRecyclerView() {
        rv_search = (RecyclerView) findViewById(R.id.recycler_search);
        rv_search.setLayoutManager(new LinearLayoutManager(this));

        apps = new ArrayList<AppModel>();

        adapter = new CommonAdapter<AppModel>(this, R.layout.item_app, apps) {
            @Override
            protected void convert(ViewHolder holder, AppModel t, final int position) {
                final AppModel app = apps.get(position);
                // holder.setImageDrawable(R.id.iv_item_app_icon,
                // app.getLocalIcon());
                ImageView iv = holder.getView(R.id.iv_item_app_icon);
                ImageLoader.getInstance().displayImage(app.getIconUrl(), iv);
                holder.setText(R.id.tv_item_app_name, app.getAppName());
                holder.setText(R.id.tv_item_app_version_name, app.getRemoteVersionName());
                holder.setRating(R.id.ratingbar_item_app_score, app.getScore());
                
                final DownloadInfo downloadInfo = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
                if (downloadInfo != null && downloadInfo.getState() == DownloadManager.FINISH) {
                    if (ApkUtils.isNeedOpen(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "打开");
                    } else if (ApkUtils.isNeedUpdate(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "更新");
                    } else {
                        if (FileUtils.isExist(downloadInfo.getTargetPath())) {
                            holder.setText(R.id.btn_item_app_install, "安装");
                        } else {
                            holder.setText(R.id.btn_item_app_install, "下载");
                        }
                    }
                } else if (downloadInfo != null && downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                    holder.setText(R.id.btn_item_app_install, "正在下载");
                } else {
                    if (ApkUtils.isNeedOpen(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "打开");
                    } else if (ApkUtils.isNeedUpdate(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                        holder.setText(R.id.btn_item_app_install, "更新");
                    } else {
                        holder.setText(R.id.btn_item_app_install, "下载");
                    }
                }
                final View button = holder.getView(R.id.btn_item_app_install);

                holder.setOnClickListener(R.id.btn_item_app_install, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());

                        if (info != null && info.getState() == DownloadManager.FINISH) {
                            if (ApkUtils.isInstalled(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                                if (!app.getAppPackName().equals(Util.getPackageName(SearchActivity.this))) {
									/*ApkUtils.openAPP(SearchActivity.this, app.getAppPackName());*/
                                    if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
                                        ApkUtils.openAPP(SearchActivity.this,
                                                app.getAppPackName());
                                    } else {//无图标打开方式

                                        ApkUtils.openAPP(SearchActivity.this,
                                                app.getAppPackName(), app.getActivity());
                                    }
                                }
                            }else {
                                if (FileUtils.isExist(info.getTargetPath())) {
                                    ApkUtils.installSilent(SearchActivity.this, new File(info.getTargetPath()));
                                }else {
                                    APPDownloadManager.removeTask(info.getTaskKey());
                                    APPDownloadManager.addTask(SearchActivity.this, app, info.getListener());
                                    startActivity(AppDownManagerActivity.class);
                                }
                            }
                        }else {
                            APPDownloadManager.addTask(SearchActivity.this, app, null);
                            startActivity(AppDownManagerActivity.class);
                        }
                  /*      // 如果该任务的状态为完成
                        if (info != null && info.getState() == DownloadManager.FINISH) {
                            // 如果已经安装则打开; 未安装,判断安装包是否存在. 如果存在则安装, 不存在则重新下载;
                            // if (ApkUtils.isAvailable(getContext(),
                            // app.getAppPackName())) {
                            if (ApkUtils.isNeedOpen(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                                if (!app.getAppPackName().equals(Util.getPackageName(SearchActivity.this))) {
                                    *//*ApkUtils.openAPP(SearchActivity.this, app.getAppPackName());*//*
                                    if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
                                        ApkUtils.openAPP(SearchActivity.this,
                                                app.getAppPackName());
                                    } else {//无图标打开方式

                                        ApkUtils.openAPP(SearchActivity.this,
                                                app.getAppPackName(), app.getActivity());
                                    }

                                }
                            } else {
                                if (FileUtils.isExist(info.getTargetPath())) {
                                    // TODO 安装
                                    ApkUtils.installSilent(SearchActivity.this, new File(info.getTargetPath()));
                                    // ApkUtils.install(SearchActivity.this, new
                                    // File(info.getTargetPath()));
                                } else {
                                    APPDownloadManager.removeTask(info.getTaskKey());
                                    APPDownloadManager.addTask(SearchActivity.this, app, info.getListener());
                                    // TODO 点击下载后跳转到下载列表页面吗?
                                    // startActivity(AppDownManagerActivity1.class);
                                    SnackbarUtil.showSnackbar(SearchActivity.this, button);
                                    empty.notifyItemChanged(position);
                                }
                            }
                        } else if (info != null && info.getState() == DownloadManager.DOWNLOADING) {
                            intent = new Intent(SearchActivity.this, AppDownManagerActivity1.class);
                            startActivity(intent);
                        } else {
                            if (ApkUtils.isNeedOpen(SearchActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
                                if (!app.getAppPackName().equals(Util.getPackageName(SearchActivity.this))) {
                                   *//* ApkUtils.openAPP(SearchActivity.this, app.getAppPackName());*//*
                                    if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
                                        ApkUtils.openAPP(SearchActivity.this,
                                                app.getAppPackName());
                                    } else {//无图标打开方式

                                        ApkUtils.openAPP(SearchActivity.this,
                                                app.getAppPackName(), app.getActivity());
                                    }
                                }
                            } else {
                                APPDownloadManager.addTask(SearchActivity.this, app, null);
                                // TODO 点击下载后跳转到下载列表页面吗?
                                // startActivity(AppDownManagerActivity1.class);
                                SnackbarUtil.showSnackbar(SearchActivity.this, button);
                                empty.notifyItemChanged(position);
                            }
                        }*/
                    }

              //=================

                });
            }
        };

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                intent = new Intent(SearchActivity.this, AppDetailActivity.class);
                AppModel app = apps.get(position);
                intent.putExtra(Constant.DATA, app);
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder,
                                           int position) {
                // TODO Auto-generated method stub
                return false;
            }
        });

        empty = new EmptyWrapper(adapter);
        empty.setEmptyView(R.layout.empty_view);

        rv_search.setAdapter(empty);

    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_toolbar_search:
                if (hasFocus) {

                }
                break;


            default:
                break;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_toolbar:
                if (checkInfo()) {
                    ToastShow.makeToast(this, "请输入搜索内容");
                    return;
                }
                search();
                break;

            default:
                break;
        }

    }

    /**
     * 检查输入内容的格式
     *
     * @return
     */
    private boolean checkInfo() {
        info = et_search.getText().toString().trim();
        if (!TextUtils.isEmpty(info)) {
            return false;
        }
        return true;
    }

    /**
     * 搜索
     */
    private void search() {
        page = 1;
        String json = GsonUtil.toQueryJson(info, URLConstants.SORT_DOWNLOAD, null, null, page);
        LogUtil.e("搜索请求" + json);
        HttpUtil.post(json, new StringDialogCallback(this, "正在搜索...") {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2,
                                   Response arg3) {
                LogUtil.e("返回搜索请求" + arg1);
                //********************************
                //TODO 上报查询行为
                String accountId = PreferenceUtils.getInstance(SearchActivity.this).getString(PreferenceKey.ACCOUNT_ID);
//				WLData.getInstance().reportEvent(accountId, Events.APP_SEARCH);
                //********************************

                JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
                }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    apps.clear();
                    apps.addAll(result.getData().getApps());
                    totalPage = result.getData().getTotalPage();
                    page++;
                    empty.notifyDataSetChanged();
                }else if(URLConstants.RetCode.TIMEOUT_ERROR.equals("result.getRetCode()")){
                    AppManager.getAppManager().finishAllActivity();
                    startActivity(new Intent(SearchActivity.this, LoginActivity.class));
                }
                else {
                    ToastShow.shortMessage(result.getRetMsg());
                }

            }

            @Override
            public void onError(boolean isFromCache, Call call,
                                Response response, Exception e) {
                if (response == null) {
                    ToastShow.shortMessage(getString(R.string.alert_failed_connect));
                }
                super.onError(isFromCache, call, response, e);
            }
        });
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        String json = GsonUtil.toQueryJson(info, URLConstants.SORT_DOWNLOAD, null, null, page);
        HttpUtil.post(json, new StringCallback() {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {

            }
        });
    }
}
